package cc.ufinity.networkdiagnose.widget;

import java.lang.reflect.Field;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.net.wifi.ScanResult;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import cc.ufinity.networkdiagnose.app.GlobalApp;
import cc.ufinity.networkdiagnose.manager.Account;
import cc.ufinity.networkdiagnose.manager.DBManager;
import cc.ufinity.networkdiagnose.manager.FTPConfig;
import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.Task;
import cc.ufinity.networkdiagnose.manager.WifiEAPManager;
import cc.ufinity.networkdiagnose.manager.WlanManager;
import cc.ufinity.networkdiagnose.util.StringUtils;
import cc.ufinity.networkdiagnose.view.R;

public class PeapTestWidgetProxy extends GeneralTestWidget {

    private WlanManager wlanManager;
    private WifiEAPManager wEapManager;
    private Handler hander;

    private Activity ctx;
    private Handler handlerChild;
    private static final String TAG = "peapAuthTest";
    private Button backBtn;
    private boolean connecting;
    private boolean isFirst = true;

    public void setConnecting(boolean connecting) {
        this.connecting = connecting;
    }

    private int current;

    public void setCurrent(int current) {
        this.current += current;
    }

    private int timeout_num;// 超时次数;

    private int frequency;
    private float totalTime;
    private Task task;
    private String failureFlag="";
    public static int testFlag = 0; 
    public static int taskFlag = 0; 
	public static String doNextTestBroadCast ="doNext1";
	public static String doNextTaskBroadCast = "doNext";
    public PeapTestWidgetProxy(Activity context, Handler handl) {
        super(context);
        inflate(context, R.layout.aprelevance_test_widget_proxy, this);
        this.ctx = context;
        this.handlerChild = handl;
        backBtn = (Button) findViewById(R.id.ap_test_proxy_btnback);
        backBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                backToTask(ctx);
            }
        });

        hander = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case MessageWhat.DO_NEXT_TEST:
                   // showNextText();
                    break;
                default:
                    update(msg.what);
                }
            }
        };

        wlanManager = new WlanManager(ctx);
        wlanManager.setHandler(hander);
        task = (Task) ctx.getIntent().getSerializableExtra(TAG_REFER_TASK);
        frequency = task.testCount;
        
//        if(!task.scanResult.SSID.equals(WlanManager.SSID_CMCC_AUTO)){
//            failureFlag="erro";
//        	wlanManager.sendMsg(MessageWhat.DONE);
//        }else if(!wlanManager.isExistConfig(WlanManager.SSID_CMCC_AUTO)){ 
//        	inputUserPassDialog() ;
//   	    }else {
//        	start(task.scanResult);
//		} 
    //修改peap 认证时cmcc-auto账号为cmcc账号    
		if (!task.scanResult.SSID.equals(WlanManager.SSID_CMCC_AUTO)) {
			failureFlag = "erro";
			wlanManager.sendMsg(MessageWhat.DONE);
		} else {
			DBManager db = new DBManager(ctx);
			Account config = db.getAccount();
			if (config != null) {
				wEapManager = new WifiEAPManager(ctx);
				wEapManager.removeEapConfig();
				wEapManager.saveEapConfig(config.password, config.userName, "");
			}
			start(task.scanResult);
		}
        
//        start(task.scanResult);

    }
    
    /**
     * 配置Peap认证的身份、匿名身份和无线密码
     * @param ctx
     * @param wlanManager
     * @param handler
     */
    public void inputUserPassDialog() {
    	LayoutInflater factory = LayoutInflater.from(ctx);
		final View dialogView = factory.inflate(R.layout.peap_input_user_pass_dialog, null);
		final EditText identText = (EditText) dialogView.findViewById(R.id.peapIdentity);
		final EditText anonIdentText = (EditText) dialogView.findViewById(R.id.peapAnonIdentity);
		final EditText passText = (EditText) dialogView.findViewById(R.id.peapPassword);
        AlertDialog.Builder builder = new AlertDialog.Builder(ctx); 
        builder.setTitle("PEAP认证账号");  
//        builder.setIcon(R.drawable.what);
        builder.setView(dialogView); 
        builder.setCancelable(false); 
        builder.setPositiveButton("配置", new DialogInterface.OnClickListener() {
        	public void onClick(DialogInterface dialog, int id) {
	       		 String identity = identText.getText().toString();
	    		 String anonident = anonIdentText.getText().toString();
	    		 String password = passText.getText().toString();
	    		 try { 
	    			 Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
					 field.setAccessible(true);
	    			 if (StringUtils.isEmpty(identity)) {
						field.set(dialog, false);
						showMessage(ctx, "请输入身份");
					 }else if (StringUtils.isEmpty(password)) {
						field.set(dialog, false);
		    			showMessage(ctx, "请输入无线密码");
					 }else{ 
						 field.set(dialog, true);
						 wEapManager = new WifiEAPManager(ctx);
						 wEapManager.saveEapConfig(password, identity,anonident); 
					     start(task.scanResult);
					 }
	    		 } catch (Exception e) {
						e.printStackTrace();
						showMessage(ctx, "配置失败，请稍后重试");
				 }
        	}
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener(){
        	public void onClick(DialogInterface dialog, int id) {
        		try {
					Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
					field.setAccessible(true);
					field.set(dialog, true);
				} catch (Exception e) {
					e.printStackTrace();
				}
        		//mSendBroadcast(ctx);
        		handlerSendToTarget(handlerChild, MessageWhat.HANDLER_PEAP);
        		dialog.cancel();
        	}
        });
	 	wifiListDialog = builder.create();
	    wifiListDialog.show(); 
 
    }
    //判断是否存在CMCC-AUTO扫描结果
    public final ScanResult retureCMCCAUTOScan(List<ScanResult> scanResults) {
        int length = scanResults.size();
        for (int i = 0; i < length;i++ ) { 
            ScanResult obj = scanResults.get(i);
            String ssid = obj.SSID;
            if(ssid!=null && ssid.equals(WlanManager.SSID_CMCC_AUTO)){
            	  //  if(ssid!=null && ssid.equals("TP-LINK_5908CC")){
            	return obj;
            }
        }
        return null;
    } 

    private final class ApTestThread extends Thread {
        private ScanResult scan;

        public ApTestThread(final ScanResult scan) {
            this.scan = scan;
        }

        @Override
        public void run() {
        	executable = true;
            while (current < frequency && executable) {
                if (!connecting) {
                    current++;
                    connecting = true;
                    try {
                    	peapTimerTask.cancel();
                    } catch(Exception e){}
                    wlanManager.connect(scan);
                    startConnectTimeoutListener();
                }
            }
        }

    }

    private void start(final ScanResult scan) {
        final FTPConfig ftp = this.getFTPConfig(ctx);
        if (ftp!=null && ftp.userName!=null && ftp.userName.length() > 0) {
            final ApTestThread apTestThread = new ApTestThread(scan);
          //  this.showProgressDialog(ctx, "正在进行Peap认证测试...", frequency);
            apTestThread.start();
        }
    }

    TimerTask peapTimerTask;
    private void startConnectTimeoutListener() {
        peapTimerTask = new TimerTask() {
            public void run() {
                if (connecting) {
                    Log.e(TAG, "Peap认证第" + current + "测试连接超时");
                    wlanManager.setConnectedConsumeTime(System.currentTimeMillis());
                    wlanManager.sendMsg(MessageWhat.WIFI_CONNECT_TIMEOUT);
                }
            }
        };
        Timer timer = new Timer();
        timer.schedule(peapTimerTask, WlanManager.CONNECT_TIMEOUT);
    }

    void update(int what) {
    	//----------------------------------------------------------
		if(isFirst) {
			isFirst = false;
			StringBuffer temp = new StringBuffer();
			GlobalApp.result_PEAP_test = temp;
		}
		//----------------------------------------------------------
        setDialogProgress(current);
        try {
        	peapTimerTask.cancel();
        } catch(Exception e){}
        switch (what) {
        case MessageWhat.WIFI_SUCESS_CONNECTED:
            if (connecting) {
                float costTime = (wlanManager.getConnectedConsumeTime() - wlanManager.getStartConntectTime()) / (float)1000;
                StringBuffer s = new StringBuffer();
                s.append("第").append(current).append("次Peap认证：");
                s.append(wlanManager.getCurrentScanResult().SSID).append(" MAC地址：");
                s.append(wlanManager.getCurrentScanResult().BSSID).append('\n');
                s.append("IP：").append(wlanManager.getIpAddress()).append(" 时间：");
                s.append(costTime).append(" s\n");
                s.append("第").append(current).append("次Peap下线成功；"); 
              //----------------------------------------------------------
        		
    			GlobalApp.result_PEAP_test.append("第").append(current).append("次Peap认证：")
    					.append(wlanManager.getCurrentScanResult().SSID)
    					.append("\nMAC地址：").append(wlanManager.getCurrentScanResult().BSSID)
    					.append("\nIP：").append(wlanManager.getIpAddress())
    					.append("时间：").append(costTime).append(" s\n")
    					.append("第").append(current).append("次Peap下线成功；");
    		
		//----------------------------------------------------------
                totalTime += costTime;
                if (current == frequency) {
                    wlanManager.sendMsg(MessageWhat.DONE);
                }
                connecting = false;
            }
            break;
        case MessageWhat.WIFI_CONNECT_TIMEOUT:
            StringBuffer s = new StringBuffer();
            s.append("第").append(current).append("次Peap认证：");
            s.append(wlanManager.getCurrentScanResult().SSID).append(" MAC地址：");
            s.append(wlanManager.getCurrentScanResult().BSSID).append("失败.");
            s.append("第").append(current).append("次Peap下线失败；");
          //----------------------------------------------------------
    		
			GlobalApp.result_PEAP_test.append("第").append(current).append("次Peap认证：")
					.append(wlanManager.getCurrentScanResult().SSID)
					.append("\nMAC地址：").append(wlanManager.getCurrentScanResult().BSSID)
					.append("失败.\n").append("第").append(current).append("次Peap下线失败；");;
	
		//----------------------------------------------------------
            setTimeoutNum(1);
            timeout_num ++;
            if (current == frequency) {
                wlanManager.sendMsg(MessageWhat.DONE);
            }
            connecting = false;
            break;
        case MessageWhat.DONE:
        	if(failureFlag !=null && failureFlag.equals("erro")) {
        		timeout_num = frequency;
        	}
        		
            s = new StringBuffer();
            DecimalFormat df = new DecimalFormat("#0.000");
            int success = frequency - timeout_num;
            if(success < 0) {
            	success = 0;
            }
            s.append("Peap认证次数：").append(frequency);
            s.append(" 认证成功次数：").append(success).append('\n');
            s.append("认证成功率：").append((float) success / frequency * 100).append('%');
            s.append(" 认证平均时延：").append(df.format((float) (totalTime / frequency))).append('s');
          //----------------------------------------------------------
    		
			GlobalApp.result_PEAP_test.append("\nPeap认证次数：").append(frequency) 
					.append("\nPeap认证成功次数：").append(success)
					.append("\n下线成功次数：").append(success)
					.append("\n认证平均时延：").append(df.format((float) (totalTime / frequency))).append(" s\n")
					.append("\n认证成功率：").append((float) success / frequency * 100).append(" %\n")
					.append("\n下线成功率：").append((float) success / frequency * 100).append(" %\n");

		//----------------------------------------------------------

            task.peapAuthAvgTime = df.format((float) (totalTime / frequency));
            if((float) (totalTime / frequency)<0.001){
            	 task.peapAuthAvgTime = "0.001";
            }
            task.peapSuccessRate = df.format((float) success / frequency * 100);
            task.peapOffSuccessRate = df.format((float) success / frequency * 100);
            
            task.peapDelay = task.peapAuthAvgTime;
            task.peapCount = task.testCount +"";
            task.peapSuccessCount = success +"";
            task.peapOffCount = success +"";
            task.peapOffSuccessCount = success +"";
            

System.out.println("task.peapCount => " + task.peapCount);
System.out.println("task.peapSuccessCount => " + task.peapSuccessCount);
System.out.println("task.peapSuccessRate => " + task.peapSuccessRate);
System.out.println("task.peapOffCount => " + task.peapOffCount);
System.out.println("task.peapOffSuccessCount => " + task.peapOffSuccessCount);
System.out.println("task.peapOffSuccessRate => " + task.peapOffSuccessRate);
System.out.println("task.peapDelay => " + task.peapDelay);
            
            ctx.getIntent().putExtra(TAG_REFER_TASK, task);

     //       this.dismissProgressDialog();
            connecting = false;
    		//mSendBroadcast(ctx);
    		handlerSendToTarget(handlerChild, MessageWhat.HANDLER_PEAP);
            break;
        }

    }

    private void setTimeoutNum(int timeout_num) {
        this.timeout_num += timeout_num;
    }
}
